package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.XMLMarshaller;
import ntu.metaweb.result.PageRating;
import ntu.metaweb.result.Title;
import ntu.metaweb.service.Service;
import ntu.metaweb.storage.WebPageQuery;
import ntu.metaweb.storage.WebPageQueryKey;
import ntu.p2p.dht.DHTContent;
import rice.Continuation;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

@SuppressWarnings("restriction")
public class GetTitleHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		if (params.get("url_parameter").equals("null"))
			params.put("url_parameter", "");
		
		final String temp = params.get("url") + params.get("url_parameter");
		
		System.out.println("get page title " + temp);
		
		final WebPageQueryKey key = 
				new WebPageQueryKey(URLDecoder.decode(params.get("url"), "UTF-8"), 
						URLDecoder.decode(params.get("url_parameter"), "UTF-8"));
		Metaweb.getInstance().getDhtApplication().lookup(key, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {
						onReceiveResult(params, exchange, null);
					}

					@Override
					public void receiveResult(DHTContent result) {
						onReceiveResult(params, exchange, result);
					}
		});
	}

	protected void onReceiveResult(HashMap<String,String> params, 
			HttpExchange exchange, DHTContent result) {
		WebPageQuery webpagequery = (WebPageQuery) result;
		Title title = new Title(webpagequery);
		byte[] temp = XMLMarshaller.getInstance().marshall(title).getBytes();
		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write(temp);
			System.out.println(XMLMarshaller.getInstance().marshall(title));

			responseBody.close();
			exchange.close();
			System.out.println("close get page rating handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close get page rating handler");
		}
	}

}
